package com.wangyu.talents.web.system.user.service.impl;

import static com.wangyu.talents.web.system.user.utils.UserUtil.matches;

import com.google.common.collect.Maps;
import com.wangyu.talents.common.config.Constants;
import com.wangyu.talents.core.service.impl.BaseServiceImpl;
import com.wangyu.talents.web.security.shiro.exception.UserNamePasswordNotMatchException;
import com.wangyu.talents.web.system.user.mapper.UserMapper;
import com.wangyu.talents.web.system.user.model.User;
import com.wangyu.talents.web.system.user.service.UserService;
import java.util.Map;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户服务层实现
 *
 * @author wangyu
 * @Date 2018-09-02 12:58
 */
@Service("userService")
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

  @Autowired
  private UserMapper userMapper;

  @Override
  public int insert(User user) {
    user.randomSalt();
    if (StringUtils.isBlank(user.getPassword())) {
      user.setPassword(Constants.INIT_PASSWORD);
    }
    user.setPassword(this.encryptPassword(user.getPassword(), user.getSalt()));
    if (StringUtils.isEmpty(user.getTrueName())) {
      user.setTrueName(user.getLoginName());
    }
    if (user.getType() == null) {
      user.setType(0);
    }
    return super.insert(user);
  }

  @Override
  public User getDetails(Long userId) {
    Map<String, Object> map = Maps.newHashMap();
    map.put("id", userId);
    User user = userMapper.findOne(map);
    return user;
  }

  @Override
  public String encryptPassword(String password, String salt) {
    return DigestUtils.md5Hex(password + salt);
  }

  @Override
  public User findByUserName(String userName) {
    return userMapper.findByUserName(userName);
  }

  @Override
  public User login(String userName, String password) {
    if (StringUtils.isEmpty(userName)) {
      return null;
    }
    User user = findByUserName(userName);
    if (user == null) {
      throw new UserNamePasswordNotMatchException("未查询到相关用户信息");
    }
    if (!matches(user, password)) {
      //loginRecordCache.put(username, ++retryCount);
      throw new UserNamePasswordNotMatchException("用户名或密码不正确");
    } else {
      //clearLoginRecordCache(username);
    }
    return user;
  }
}
